<template>
  <div class="app-container">

    <el-card shadow="always">
      <div>
        <div class="flex justify-between align-center">
          <div>
            <p><span style="color:#fd2f2f;">当前美国时区:(-7)：{{ us_time | parseTime('y-m-d h:i:s 星期a') }}</span>
              <span style="color:#fd2f2f;">,当前欧洲时区:(+2)：{{ eur_time | parseTime('y-m-d h:i:s 星期a') }}</span>
            </p>
          </div>
        </div>
      </div>

      <el-form v-show="showSearch"
               ref="queryForm"
               label-width="120px"
               @keyup.enter.native="submitSearch"
               @submit.native.prevent>
        <el-row>
          <el-col :md="12"
                  :sm="12"
                  style="margin-bottom: 10px;">
            <el-form-item label="时间:">
              <el-radio-group @change="day_change"
                              v-model="saleSearch.dateType"
                              size="small"
                              class="mr5">
                <el-radio-button :label="0">今天</el-radio-button>
                <el-radio-button :label="1">昨天</el-radio-button>
                <el-radio-button :label="2">最近7天</el-radio-button>
                <el-radio-button :label="3">本月</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :md="12"
                  :sm="12"
                  style="margin-bottom: 10px;">
            <el-form-item label="店铺:">
              <template>
                <el-select v-model="saleSearch.site_id"
                           filterable
                           multiple
                           @change="select_change"
                           collapse-tags
                           style="min-width:300px"
                           placeholder="选择店铺">
                  <el-option v-for="item in site_arr"
                             :key="item.id"
                             :label="item.site_name"
                             :value="item.id">
                    <span style="float: left">{{ item.site_name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.site_number }}</span>
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="12"
                  :sm="12"
                  style="margin-bottom: 10px;">
            <el-form-item label="时间段:">
              <el-date-picker v-model="saleSearch.datetime"
                              type="daterange"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :md="12"
                  :sm="12"
                  style="margin-bottom: 10px;">
            <el-form-item class="ele-text-right"
                          label-width="50px">
              <el-button type="primary"
                         size="mini"
                         @click="searchs"
                         icon="el-icon-search"
                         class="ele-btn-icon">搜索 </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </el-card>
    <el-card shadow="always"
             body-style="padding:0 20px;"
             v-loading="loading">
      <el-divider class="mt5 mb5" />
      <el-row>
        <!-- <el-descriptions title="明细">
                    <el-descriptions-item label="美金$">{{arr_two.sales_usd}}</el-descriptions-item>
                    <el-descriptions-item label="欧元€">{{arr_two.sales_eur}}</el-descriptions-item>
                    <el-descriptions-item label="争议单">{{arr_two.dispute}}</el-descriptions-item>
                    <el-descriptions-item label="退款单">{{arr_two.refund}}</el-descriptions-item>
                    <el-descriptions-item label="授权单">{{arr_two.authorized}}</el-descriptions-item>
                    <el-descriptions-item label="毛利$">{{arr_two.gross_profit}}</el-descriptions-item>
                </el-descriptions> -->
        <!-- <p style="">{{arr_two.gross_profit_handle1}}</p>
                <p style="">{{arr_two.gross_profit_handle2}}</p> -->
        <!-- <span style="">{{sales_handle}}</span>
                    <span style="">{{paid_handle}}</span>
                    <p style="">{{gross_profit_handle}}</p> -->
        <!-- <el-divider class="mt5 mb5" /> -->
        <template>
          <el-table :data="arr"
                    border
                    :default-sort="{prop: 'date', order: 'descending'}"
                    style="width: 100%">
            <el-table-column prop="sales"
                             label="销售额$">
            </el-table-column>
            <el-table-column prop="paid"
                             label="总单量">
            </el-table-column>
            <el-table-column prop="refund_money"
                             label="退款金额$">
            </el-table-column>
            <el-table-column prop="sales_usd"
                             label="美金$">
            </el-table-column>
            <el-table-column prop="sales_eur"
                             label="欧元€">
            </el-table-column>
            <el-table-column prop="dispute"
                             label="争议单">
            </el-table-column>
            <el-table-column prop="refund"
                             label="退款单">
            </el-table-column>
            <el-table-column prop="authorized"
                             label="授权单">
              <template slot-scope="scope">
                <el-popover placement="top-start"
                            title="备注"
                            trigger="hover"
                            :content="scope.row.authorized_info">
                  <el-button size="small"
                             type="warning"
                             slot="reference">{{ scope.row.authorized }}</el-button>
                </el-popover>
                <!-- <p>{{ scope.row.authorized }}:{{ scope.row.authorized }}{{ scope.row.authorized }}</p> -->
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template>
          <el-table :data="arr"
                    border
                    :default-sort="{prop: 'date', order: 'descending'}"
                    style="width: 100%">
            <el-table-column prop="gross_profit"
                             label="预估毛利$=">
            </el-table-column>
            <el-table-column prop="sales"
                             label="销售额$-">
            </el-table-column>
            <el-table-column prop="adv_cost"
                             label="预估广告$-">
            </el-table-column>
            <el-table-column prop="logistics"
                             label="物流$-">
            </el-table-column>
            <el-table-column prop="purchase"
                             label="采购$-">
            </el-table-column>
            <el-table-column prop="platform_discount"
                             label="手续费(6%)">
            </el-table-column>
          </el-table>
        </template>
      </el-row>
    </el-card>
    <el-card shadow="always"
             body-style="padding:0 20px;"
             v-loading="loading">
      <el-divider class="mt5 mb5" />
      <el-row>
        <div>店铺业绩</div>
        <el-divider class="mt5 mb5" />
        <template>
          <el-table :data="shopify_sales"
                    border
                    :summary-method="getSummaries"
                    show-summary
                    :row-class-name="tableRowClassName"
                    :cell-style="columnStyle"
                    :default-sort="{prop: 'date', order: 'descending'}"
                    style="width: 100%">
            <el-table-column prop="name"
                             label="店铺">
            </el-table-column>
            <el-table-column prop="sales"
                             label="销售额$"
                             sortable>
            </el-table-column>
            <el-table-column label="运营明细"
                             width="150">
              <template slot-scope="scope">
                <template v-for="(item, index) in scope.row.remarks_operations">
                  <div v-if="scope.row.name != 'SheCurve'"
                       :key="index">
                    <!-- <p><span style="font-weight: bold;">{{ item.label_type }}</span>:{{ item.nickname }}</p>
                                                <p><span style="font-weight: bold;">{{ item.currency }}{{ item.total }}</span>  单量:{{ item.counts }}</p> -->
                    <p>{{ item.nickname }}:{{ item.currency }}{{ item.total }}</p>
                  </div>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="count"
                             sortable
                             label="单量">
            </el-table-column>
            <el-table-column prop="zadvcost_new"
                             sortable
                             label="预估广告$">
            </el-table-column>
            <el-table-column prop="zadvcost_msg2"
                             sortable
                             label="广告明细">
            </el-table-column>
            <el-table-column prop="gross_profit"
                             sortable
                             label="预估毛利$">
            </el-table-column>
            <el-table-column prop="refund"
                             label="退款金额$">
            </el-table-column>
            <el-table-column prop="roi"
                             sortable
                             label="ROI">
            </el-table-column>
            <el-table-column prop="freight"
                             sortable
                             label="物流预估">
            </el-table-column>
            <el-table-column prop="material"
                             sortable
                             label="采购预估">
            </el-table-column>
            <!-- <el-table-column
                                    :show-overflow-tooltip="true"
                                    prop="remarks"
                                    label="备注">
                                </el-table-column> -->
            <!-- <el-table-column label="操作" align="left">
                                    <template slot-scope="scope">
                                        <el-button class="btn-mar" size="mini" type="primary" @click="handleEdit(scope.row)">详情</el-button>
                                    </template>
                                </el-table-column> -->
          </el-table>
        </template>
      </el-row>
    </el-card>
    <el-card shadow="always"
             body-style="padding:0 20px;"
             v-loading="loading">
      <div style="margin:10px 0;">业绩分配</div>
      <el-table :data="tableData"
                border>
        <el-table-column prop="tag_source"
                         label="渠道"
                         width="100">
        </el-table-column>
        <el-table-column prop="total_price"
                         label="销售额"
                         sortable>
        </el-table-column>
        <el-table-column prop="tag_campaign"
                         label="运营"
                         sortable>
        </el-table-column>
        <el-table-column prop="advcost"
                         label="广告成本"
                         sortable>
        </el-table-column>
        <el-table-column prop="roi"
                         label="ROI"
                         sortable>
        </el-table-column>
        <el-table-column prop="currency"
                         label="币种"
                         sortable>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <el-dialog :title="!disabled ? '编辑' : '详情'"
               :visible="editOpen"
               :before-close="beforeClose"
               destroy-on-close>
      <EditForm ref="editForm"
                :findFormData="findFormData"
                :disabled="disabled"
                @submitForm="submitForm"
                :editFormParams="editFormParams"
                @editFormCancel="beforeClose" />
    </el-dialog>

  </div>
</template>

<script>
import { curdMixin } from '@/mixins/curdMixin'
import EditForm from './EditFormCom'
import { mapGetters } from 'vuex'
export default {
  name: 'dashboardshop',
  mixins: [curdMixin],
  components: { EditForm },
  data () {
    return {
      site_arr: [],
      loading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7 - 3600 * 1000 * 15);
            end.setTime(end.getTime() - 3600 * 1000 * 15);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 - 3600 * 1000 * 15);
            end.setTime(end.getTime() - 3600 * 1000 * 15);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90 - 3600 * 1000 * 15);
            end.setTime(end.getTime() - 3600 * 1000 * 15);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      saleSearch: {
        site_id: [],
        dateType: 1,
        datetime: '',
      },
      time: 0,
      start_time: new Date(),
      end_time: new Date(),
      us_time: 0,
      eur_time: 0,
      // 接口地址
      api: {
        edit: `/admin/index/dashboard_new_edit`,
      },
      editFormParams: {
      },
      day_changes: 0,
      sales_handle: '',
      paid_handle: '',
      gross_profit_handle: '',
      post_start_time: '',
      post_end_time: '',

      // 查询表单数据
      findFormData: {},
      // 是否展示编辑
      editOpen: false,

      shopify_sales: [
        {
          name: '',
          sales: '',
          count: '',
          refund: '',
          zadvcost_new: '',
          zadvcost_msg2: '',
          roi: '',
          nickname: '',
          remarks: '',
        },
      ],
      arr_two: [],
      arr: [
        {
          paid: 0,
          purchase: 0,//采购成本
          logistics: 0,//物流成本
          refund: 0,
          refund_money: 0,
          authorized: 0,
          dispute: 0,
          sales: 0,
          sales_usd: 0,
          sales_eur: 0,
          adv_cost: 0,
          estimated_cost: 0,
          platform_discount: 0,
          gross_profit: 0,
          roi: 0,
        },
      ],
      tableData: []
    }
  },
  computed: {
    ...mapGetters(['avatar', 'nickname', 'groups_name']),
  },
  created () {
    this.now();
    this.site();
    this.day_change(1);
  },
  methods: {
    // 北京时间
    now () {
      this.us_time = new Date().getTime() - 15 * 3600 * 1000;
      setInterval(() => {
        this.us_time = new Date().getTime() - 15 * 3600 * 1000;
      }, 1000)
      this.eur_time = new Date().getTime() - 6 * 3600 * 1000;
      setInterval(() => {
        this.eur_time = new Date().getTime() - 6 * 3600 * 1000;
      }, 1000)
    },
    searchs () {
      this.saleSearch.dateType = -1;
      this.day_changes = 101;
      if (this.saleSearch.datetime == undefined || this.saleSearch.datetime == null || this.saleSearch.datetime == '') {
        this.$message.error('请筛选时间');
        return false;
      } else {
        this.start_time = this.saleSearch.datetime[0]
        this.end_time = this.saleSearch.datetime[1]
      }
      this.handleSkuFind();
    },
    select_change (val) {
      this.handleSkuFind();
    },
    day_change (val) {
      this.saleSearch.datetime = '';
      if (val == 0) {
        this.saleSearch.dateType = -1;
        this.$message('未生成今日报表');
        return false;
      }
      let start_time2 = new Date();
      if (val == 0) {
        this.start_time.setTime(start_time2.getTime() - 15 * 3600 * 1000);
        this.end_time.setTime(start_time2.getTime() + 9 * 3600 * 1000);
      } else if (val == 1) {
        this.start_time.setTime(start_time2.getTime() - 3600 * 1000 * 24 - 15 * 3600 * 1000);
        this.end_time.setTime(start_time2.getTime() - 15 * 3600 * 1000);
      } else if (val == 2) {
        this.start_time.setTime(start_time2.getTime() - 3600 * 1000 * 24 * 7 - 15 * 3600 * 1000);
        this.end_time.setTime(start_time2.getTime() - 15 * 3600 * 1000);
      } else if (val == 3) {
        this.start_time.setTime(start_time2.getTime() - 15 * 3600 * 1000);
        this.end_time.setTime(start_time2.getTime() - 15 * 3600 * 1000);
      }
      this.day_changes = val;
      this.handleSkuFind();
    },

    async site () {
      let response = await this.request.post('/admin/index/dashboard_site', {})
      if (response.code == 1) {
        this.site_arr = response.data;
      }
    },
    // sku生成回显
    async handleSkuFind () {
      if (this.start_time == undefined || this.end_time == undefined) {
        let start_time2 = new Date()
        start_time2.setTime(start_time2.getTime() - 3600 * 1000 * 24 * 1);
        this.start_time = start_time2;
        this.end_time = new Date();
      }
      let start_time = Date.parse(new Date(this.start_time));
      let end_time = Date.parse(new Date(this.end_time));
      start_time = Math.round(start_time) / 1000;
      end_time = Math.round(end_time) / 1000;
      this.loading = true;
      let response = await this.request.post('/admin/index/dashboard_shop', {
        day_changes: this.day_changes,
        site_id: this.saleSearch.site_id,
        start_time: start_time,
        end_time: end_time
      })
      this.loading = false;
      if (response.code == 1) {
        this.shopify_sales = response.data.shopify_sales;
        this.arr = response.data.arr;
        this.arr_two = response.data.arr[0];
        this.sales_handle = response.data.sales_handle;
        this.paid_handle = response.data.paid_handle;
        this.gross_profit_handle = response.data.gross_profit_handle;
        this.post_start_time = response.data.start_time;
        this.post_end_time = response.data.end_time;
        this.tableData = response.data.sales_performance_list
      } else {
        this.shopify_sales = [];
        this.arr = [];
        this.arr_two = [];
        this.sales_handle = '';
        this.paid_handle = '';
        this.gross_profit_handle = '';
        this.post_start_time = '';
        this.post_end_time = '';
        this.tableData = []
      }

    },


    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '统计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (index === 8 || index === 5) {
            sums[index] = '';
          } else {
            sums[index] = sums[index].toFixed(2);
          }
        } else {
          sums[index] = 'N/A';
        }
      });
      return sums;
    },
    // 表格列背景色
    columnStyle ({ row, column, rowIndex, columnIndex }) {

    },
    // 表格行背景色
    tableRowClassName ({ row, rowIndex }) {

    },
    // 编辑
    handleEdit (row) {
      this.handleFind(row[this.primaryKey])
    },

    // 编辑回显
    async handleFind (id) {
      let response = await this.request.get(this.api.edit, {
        params:
        {
          post_start_time: this.post_start_time,
          post_end_time: this.post_end_time,
          id: id,
        }
      })
      this.findFormData = this.formatFindData(response.data)
      this.editOpen = true
    },
  },
}
</script>

<style lang="scss" scoped>
.app-container {
    background: #f0f2f5;
    .title-tip {
        color: #909399;
        margin: 0;
        display: block;
    }
    /* 统计卡片 */
    .chart-card {
        color: #606266;
        margin-bottom: 15px;
    }
    .chart-card-num {
        font-size: 30px;
    }

    .chart-card-content {
        height: 50px;
        box-sizing: border-box;
        margin-bottom: 12px;
        font-size: 13px;
    }

    .chart-card-text {
        font-size: 13px;
    }
}
</style>
